package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constants.WareConstants;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService detailService;

    @Autowired
    WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);
    }

    //合并采购需求
    @Transactional
    @Override
    public R merge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //没有选择采购单 新建一个采购单
        if(purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstants.PurchaseStatusEnum.CREATED.getCode());

            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //有采购单， 判断采购单状态 只有 0/1[新建，已分配]才能合并到采购单上
        PurchaseEntity byId = this.getById(purchaseId);   //1
        if(byId.getStatus() > WareConstants.PurchaseStatusEnum.ASSIGNED.getCode()){
            throw new RuntimeException("合并采购单错误.");
        }


        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntities = items.stream().map(id -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(id);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstants.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        detailService.updateBatchById(detailEntities);

        //合并完采购单最后再给采购单修改日期，改为当前日期。
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(finalPurchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
        return R.ok();
    }

    @Override
    @Transactional
    public void received(List<Long> purchaseIds) {
        //确认采购单是新建或已分配状态
        if(!CollectionUtils.isEmpty(purchaseIds)){
            //获取订单详细信息
            List<PurchaseEntity> purchaseEntities = (List<PurchaseEntity>) this.listByIds(purchaseIds);

            List<PurchaseEntity> collect = purchaseEntities.stream().filter(item -> {
                return item.getStatus() <= WareConstants.PurchaseStatusEnum.ASSIGNED.getCode();
            }).map(item -> {
                //修改采购单状态 和最后修改时间。
                item.setStatus(WareConstants.PurchaseStatusEnum.RECEIVE.getCode());
                item.setUpdateTime(new Date());
                return item;
            }).collect(Collectors.toList());

            this.updateBatchById(collect);

            List<Long> ids = collect.stream().map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            //修改采购项状态。
            detailService.updateDetailByPurchaseIds(ids,WareConstants.PurchaseDetailStatusEnum.BUYING.getCode());
        }
    }

    //完成采购
    @Override
    @Transactional
    public void done(PurchaseDoneVo purchaseDoneVo) {
        boolean flag = true;

        ArrayList<PurchaseDetailEntity> updateDetail = new ArrayList<>();

        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            //判断提交采购项状态 是否有异常
            if(item.getStatus() == WareConstants.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;  //有异常
                detailEntity.setStatus(item.getStatus());
            }else{
                detailEntity.setStatus(item.getStatus());
                //3. 将成功采购的采购项存入库中。
                PurchaseDetailEntity byId = detailService.getById(item.getItemId());
                wareSkuService.addSkuStock(byId.getSkuId(),byId.getSkuNum(),byId.getWareId());
            }
            detailEntity.setId(item.getItemId());
            updateDetail.add(detailEntity);
        }
        //2. 修改采购项状态
        detailService.updateBatchById(updateDetail);

        //1. 根据采购情况，修改采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
        purchaseEntity.setStatus(flag?WareConstants.PurchaseStatusEnum.FINISH.getCode() //完成
                :WareConstants.PurchaseStatusEnum.HASERROR.getCode()); //有异常
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }


}